<!DOCTYPE html>
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		body,
		html,
		#allmap {
			width: 100%;
			height: 100%;
			margin: 0;
			font-family: "微软雅黑";
		}

		#popup, #error {
			position: fixed;
			z-index: 2;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.6);
			top: 0;
			left: 0;
			display: none;
		}

		.popupContent {
			position: fixed;
			z-index: 3;
			top: 50%;
			left: 50%;
			width: 200px;
			height: 100px;
			line-height: 100px;
			text-align: center;
			margin: -50px 0 0 -100px;
			background: rgba(255, 255, 255, 0.8);
		}
	</style>

	<script type="text/javascript"
		src="http://api.map.baidu.com/api?v=2.0&ak=8NIpDnteMgbZWXpvSTZxvVGWMEpQLcr1"></script>
	<script type="text/javascript"
		src="http://api.map.baidu.com/library/DistanceTool/1.2/src/DistanceTool_min.js"></script>

	<script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
	<title>百度地图</title>
</head>

<body style="display: flex;">
	<div id="allmap" style="width: 800px; display: inline-block; height: 100%;"></div>

	<div style="display: inline-block; height: 100%; margin: 40px;">
		<div>操作步骤</div>
		<div>
			1. 输入地址
			2. 选择正确的地址
			3. 根据正确的地址展示附件的 "维修" 信息
		</div>

		<div>范围：<span id="searchRange"></span></div>
		<input id="address" style="width: 400px; height: 30px;" placeholder="比如: 江苏省南京市江宁区万安西路65" />
		<div id="bdAddress" style="margin: 20px 40px;"></div>
		<div style="display: flex;">
			<div id="results" style="width: 400px; display: inline-block;"></div>
			<div id="resultsExtend" style="width: 420px; display: inline-block; font-size: 15px;"></div>
		</div>
	</div>

	<div id="popup">
		<div class="popupContent">
			加载中......
		</div>
	</div>

	<div id="error">
		<div class="popupContent">
			
		</div>
	</div>
</body>

</html>

<script type="text/javascript">
	Array.prototype.duplicate = function () {
		var tmp = [];
		this.concat().sort().sort(function (a, b) {
			if (a == b && tmp.indexOf(a) === -1) tmp.push(a);
		});
		return tmp;
	}
</script>

<script type="text/javascript">
	// 百度地图API功能
	var map = new BMap.Map("allmap");    // 创建Map实例
	map.centerAndZoom(new BMap.Point(116.404, 39.915), 19);  // 初始化地图,设置中心点坐标和地图级别
	//添加地图类型控件
	map.addControl(new BMap.MapTypeControl({
		mapTypes: [
			BMAP_NORMAL_MAP,
			BMAP_HYBRID_MAP
		]
	}));
	//默认定位 start
	map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
	map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
	//默认定位 end

	//测距插件 start {
	var myDis = new BMapLib.DistanceTool(map); //测距插件
	map.enableScrollWheelZoom(); // 启用滚轮放大缩小。
	map.enableKeyboard(); // 启用键盘操作。
	map.addControl(new BMap.ScaleControl()); // 添加比例尺控件
	map.addControl(new BMap.OverviewMapControl()); //添加缩略地图控件
	var contextMenu = new BMap.ContextMenu();//创建右键对象
	var txtMenuItem = [{
		text: '折线测距', callback: function () { myDis.open() }
	}];

	for (var i = 0; i < txtMenuItem.length; i++) {
		contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
		if (i == 1 || i == 3) {
			contextMenu.addSeparator();
		}
	}
	map.addContextMenu(contextMenu);
	//测距插件 end }
</script>

<script type="text/javascript">

	let arr = [];
	let fanweiIndex = 3;
	let address = ''

	$(function () {
		//输入地址
		$("#address").change(function (e) {
			address = e.target.value
			if (!address) return
			const reg = /.+?(省|自治区|自治州|市|地区|县|(?<!小)区|镇)/g //大兴安岭地区
			arr = address.match(reg)
			let city = arr[0].split('(')
			if (city.length >= 2) {
				arr[0] = city[1]
			}

			let arrExtend = arr.duplicate()
			console.log('------------')
			console.log(arrExtend)
			if (arrExtend && arrExtend.length) {
				alert("地址中存在重复的 省|自治区|自治州|市|县|区|镇 ，请去掉重复")
				return
			}
			let hasProvince = 0
			let hasCity = 0
			let hasCounty = 0
			let hasTown = 0
			arr.forEach((item, index) => {
				if (/.+?(省|自治区)/g.test(item)) {
					hasProvince++
				}
				if (/.+?(自治州|市|地区)/g.test(item)) {
					hasCity++
				}
				if (/.+?(县|(?<!小)区)/g.test(item)) {
					hasCounty++
				}
				if (/.+?(镇)/g.test(item)) {
					hasTown++
				}
			})

			if(hasProvince >= 2){
				alert("地址中存在多个的 省|自治区 ，请去掉重复")
				return
			}

			if(hasCity >= 2){
				alert("地址中存在多个的 自治州|市|地区 ，请去掉重复")
				return
			}

			if(hasCounty >= 2){
				alert("地址中存在多个的 区|县 ，请去掉重复")
				return
			}

			if(hasTown >= 2){
				alert("地址中存在多个的 镇 ，请去掉重复")
				return
			}

			console.log(arr)
			//范围 start
			let arrRadios = arr.map((item, index) => {
				return `<label onclick='changeRadio(this)'>
							<input type="radio" name="fanwei" value=${index} ${index == arr.length - 1 ? 'checked' : ''} />${item}
						</label>`
			})
			$("#searchRange").html(arrRadios.join(''))
			//范围 end
			document.getElementById("results").innerHTML = ''

			// 创建地址解析器实例
			fanweiIndex = arr.length - 1
			renderAddress(arr)
		});
	})

	function renderAddress(arr) {
		//清空
		map.clearOverlays();
		var myGeo = new BMap.Geocoder();
		// 将地址解析结果显示在地图上,并调整地图视野
		console.log("-----address-------")
		console.log(address)
		myGeo.getPoint(address, function (point) {
			if (point) {
				map.centerAndZoom(point, 19);
				map.addOverlay(new BMap.Marker(point, { icon: new BMap.Icon('cur.gif', new BMap.Size(50, 50), { imageSize: new BMap.Size(50, 50) }) }));

				$('#popup').show()
				var local = new BMap.LocalSearch(map, {
					renderOptions: { map: map },
					autoViewport: true,
					onSearchComplete: function (results) {
						if (local.getStatus() == BMAP_STATUS_SUCCESS) {
							// 判断状态是否正确      
							var s = [];
							for (var i = 0; i < results.getCurrentNumPois(); i++) {
								console.log(results.getPoi(i))
								s.push(`<label style="margin:0 0 10px 10px; display: block;" onclick='selectAddress(${JSON.stringify(results.getPoi(i))})'>
											<div>
												<span style="color:red; margin-right: 10px;">&#${65 + i}</span>
												<input type="radio" name="address" value="${i}" />
												<span>${results.getPoi(i).title}</span>
											</div>
											${results.getPoi(i).address}
										</label>`);
							}
							document.getElementById("resultsExtend").innerHTML = s.join('');
						} else {
							alert("您选择地址没有解析到结果!");
						}
						$('#popup').hide()
					}
				});
				let key = address.replace(arr.join(''))
				local.searchNearby(key ? key : '', arr[fanweiIndex]);
			} else {
				alert("您选择地址没有解析到结果!");
			}
		}, arr[0]);
	}

	function selectAddress(obj) {
		$("#bdAddress").text(obj.address)
		map.clearOverlays();
		if (obj.point) {
			map.centerAndZoom(obj.point, 19);
			map.addOverlay(new BMap.Marker(obj.point, { icon: new BMap.Icon('cur.gif', new BMap.Size(50, 50), { imageSize: new BMap.Size(50, 50) }) }));

			showInfo()
		} else {
			alert("您选择地址没有解析到结果!");
		}
	}

	function showInfo() {
		$('#popup').show()
		var local = new BMap.LocalSearch(map, {
			renderOptions: { map: map, panel: "results" },
			autoViewport: true,
			onSearchComplete: function (results) {
				if (local.getStatus() == BMAP_STATUS_SUCCESS) {
					// 判断状态是否正确      
					var s = [];
					for (var i = 0; i < results.getCurrentNumPois(); i++) {
						console.log(results.getPoi(i))
						let addressExtend = results.getPoi(i).address
						arr.forEach(item => {
							addressExtend = addressExtend.replace(item, '')
						});
						let href = `https://www.baidu.com/s?wd=${arr.join("")} ${addressExtend} ${results.getPoi(i).title} 电话`
						s.push(`<div style="margin:0 0 10px 10px;">
									<div>
										<span style="color:red; margin-right: 10px;">&#${65 + i}</span>
										<a target="_blank" href='${href}'>${results.getPoi(i).title}</a>
									</div>
									<a target="_blank" href='${href}'>${results.getPoi(i).address}</a>
									<div style="display:${results.getPoi(i).phoneNumber ? 'block' : 'none'}">
										<input value="${results.getPoi(i).phoneNumber}" />
										<span style="color:#4395ff; margin: 0 0 0 20px; cursor: pointer;" onclick="copyLink(this)">复制</span>
									</div>
								</div>`);
					}
					document.getElementById("resultsExtend").innerHTML = s.join('');
				} else {
					alert("您选择地址没有解析到结果!");
				}
				$('#popup').hide()
			}
		});
		local.searchNearby('维修', arr[fanweiIndex]);
	}

	function changeRadio(e) {
		fanweiIndex = parseInt(e.children[0].value)
		showInfo(arr)
	};

	function copyLink(that) {
		var e = that.previousElementSibling;
		e.select(); // 选择对象
		document.execCommand("Copy"); // 执行浏览器复制命令
	}
</script>

<script type="text/javascript">
	function render1(arr) {
		//清空
		map.clearOverlays();
		var myGeo = new BMap.Geocoder();
		// 将地址解析结果显示在地图上,并调整地图视野
		console.log("-----address-------")
		console.log(address)
		myGeo.getPoint(address, function (point) {
			console.log("-----point-------")
			console.log(point)
			if (point) {
				map.centerAndZoom(point, 19);
				map.addOverlay(new BMap.Marker(point, { icon: new BMap.Icon('cur.gif', new BMap.Size(50, 50), { imageSize: new BMap.Size(50, 50) }) }));

				var local = new BMap.LocalSearch(map, {
					renderOptions: { map: map, panel: "results" },
					autoViewport: true,
					onSearchComplete: function (results) {
						if (local.getStatus() == BMAP_STATUS_SUCCESS) {
							// 判断状态是否正确      
							var s = [];
							for (var i = 0; i < results.getCurrentNumPois(); i++) {
								let addressExtend = results.getPoi(i).address
								arr.forEach(item => {
									addressExtend = addressExtend.replace(item, '')
								});
								let href = `https://www.baidu.com/s?wd=${arr.join("")} ${addressExtend} ${results.getPoi(i).title} 电话`
								s.push(`<div style="margin:0 0 10px 10px;"><div><span style="color:red; margin-right: 10px;">&#${65 + i}</span><a target="_blank" href='${href}'>${results.getPoi(i).title}</a></div><a target="_blank" href='${href}'>${results.getPoi(i).address}</a></div>`);
							}
							document.getElementById("resultsExtend").innerHTML = s.join('');//.join("<br>");
						}
					}
				});
				//local.search("电器维修");
				local.searchNearby(address, arr[fanweiIndex]);
				//$.hulla.closed()
			} else {
				//$.hulla.closed()
				alert("您选择地址没有解析到结果!");
			}
		}, arr[0]);
	}
</script>